/**
 * 
 */
package it.robertobifulco.ias.rolemanager;

/**
 * The main role management subsystem. Every information about Roles come from this class.
 * The RoleManager can operate in 2 ways: repository in RAM or not.
 * The first way makes the application faster because all roles' informations are stored in RAM instead of
 * repository (wich is a File or a DBMS). The second one, is slower but reduced the RAM usage.
 * 
 * Note that the repository in RAM way make the application start up slower due to the repository load time.
 * More over, the repository in RAM needs application restart in order that role's modifications take effects.
 * 
 * @author Roberto Bifulco oltremago@gmail.com
 *
 */
public class RoleManager {
	
	private RoleRepository repository;
	private Role[] roleList;
	
	private boolean repositoryInRAM = false;
	
	
	
	/**
	 * @param repository the role repository
	 * @param repositoryInRAM the way the repository is managed
	 */
	public RoleManager(RoleRepository repository, boolean repositoryInRAM) {
		super();
		this.repository = repository;
		this.repositoryInRAM = repositoryInRAM;
		
		if(this.repositoryInRAM){
			try {
				String[] roles = this.repository.getRoles();
				this.roleList = new Role[roles.length];
				Role role;
				for(int i=0; i < roles.length ; ++i){
					role = new Role(roles[i],this.repository.getRoleOperations(roles[i]));
					this.roleList[i] = role;
				}
			} catch (RoleUndefinedException e) {
				throw new RuntimeException(e);
			}
		}
	}


	/**
	 * Return the Role object that corresponds to the given name
	 * 
	 * @param name
	 * @return
	 * @throws RoleUndefinedException
	 */
	public Role getRole(String name) throws RoleUndefinedException{
		
		if (!this.repositoryInRAM) {
			return new Role(name, this.repository.getRoleOperations(name));
		}
		
		for(int i=0; i<this.roleList.length ; ++i){
			if(this.roleList[i].getName().equals(name)){
				return this.roleList[i];
			}
		}
		
		throw new RoleUndefinedException("The role \"" + name + "\" is undefined");
	}

}
